package com.example.hans.obtainimagebyinternet;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/*
教程：https://blog.csdn.net/bo543937071/article/details/53380651
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener, OkHttpUtil.OnNeedSendMessageInterface{

    private ImageView mImageView[] = new ImageView[2];
    private TextView mTextView;
    private Bitmap bitmap = null;

    private OkHttpUtil okHttpUtil = new OkHttpUtil();

    private static int FALL = 0;
    // 获取img标签正则
    private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
    // 获取src路径的正则
    private static final String IMGSRC_REG = "http:\"?(.*?)(\"|>|\\s+)";

    private String strImgALL = "";
    private String[] strImg = new String[100];


    private int k = 0;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    if(k < 2) {
                        byte[] Picture = (byte[]) msg.obj;
                        bitmap = BitmapFactory.decodeByteArray(Picture,0,Picture.length);
                        mImageView[k++].setImageBitmap(bitmap);
                    }

                    break;
                }
                case 2: {
                    String str = (String)msg.obj;
                    strImgALL = str;
                    getImgaURLArray();
                    mTextView.setText(str);
                    break;
                }
                case 0:
                    Toast.makeText(MainActivity.this, "网络出现了问题", Toast.LENGTH_SHORT).show();
                    break;
                default:
            }
        }
    };

    private void init() {
        mImageView[0] = findViewById(R.id.iv_img);
        mImageView[1] = findViewById(R.id.iv_img1);
        mTextView = findViewById(R.id.tv_describe);

        okHttpUtil.setOnNeedSendMessageInterface(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();

        String url = "http://s16.sinaimg.cn/orignal/89429f6dhb99b4903ebcf&690";
        //bitmap = OkHttpUtil.getOkHttpBitmap(url);


        mTextView.setText("Hello world");
        getOkHttpBitmap(url);

        url = "http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1";
        okHttpUtil.getOkHttpString(url);

//        List<String> imgList = getImageUrl(strImgALL);
//        imgList = getImageSrc(imgList);
//        getOkHttpBitmap(imgList.get(0));


//        getOkHttpBitmap("https://cn.bing.com/az/hprichbg/rb/OyamaLeaves_ZH-CN10033445271_1920x1080.jpg");

    }

    public void getImgaURLArray() {

//        String reg = "<img src=\"(.*?)\">";
        String reg, temp;
        //reg = "<img.*? src=\\\"?(.*?\\\\.(jpg|gif|bmp|bnp|png))\\\".*? />";
//        reg = "src=\"(.*?\.(jpg|gif|bmp|bnp|png))\"";
//        reg = "src=\"((.*?).(jpg|gif|bmp|bnp|png))\"";

//        strImgALL = "tartdate>20181117</\r\n" +
//                "startdate><fullstartdate>20\r\n" +
//                "1811170800</fullstartda te><enddate>20181118</\r\n" +
//                "enddate><url>/az/hprichbg/" +
//                "rb/GeorgiaAquarium_ZH-CN12748518316_1366×768.jpg</" +
//                "url><urlBase>/az/hprichbg/\r\n" +
//                "rb/GeorgiaAquarium_ZH-\r\n" +
//                "A1407A0c1011c/";
        Log.d("TAG11111111","img标签===》"+strImgALL);
        reg = "<url>(.+?)</url>";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(strImgALL);//strImgALL为网页源码
        //使用find()方法查找第一个匹配的对象
        boolean result = matcher.find();

        int count = 0;
        //使用循环找出 html里所有的img标签
        while(result) {
            //继续查找下一个匹配对象
//            System.out.println("img标签===》"+matcher.group());

            temp = matcher.group(1);
            Log.d("TAG11111111","img标签===》"+temp);
            strImg[count++] = "http://cn.bing.com"+temp;

//            getOkHttpBitmap("https://cn.bing.com/az/hprichbg/rb/OyamaLeaves_ZH-CN10033445271_1920x1080.jpg");

            getOkHttpBitmap(strImg[count-1]);

            result = matcher.find();
        }
    }

    private List<String> getImageUrl(String HTML) {
        Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML);
        List<String> listImgUrl = new ArrayList<String>();
        while (matcher.find()) {
            listImgUrl.add(matcher.group());
        }
        return listImgUrl;
    }


    private List<String> getImageSrc(List<String> listImageUrl) {
        List<String> listImgSrc = new ArrayList<String>();
        for (String image : listImageUrl) {
            Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image);
            while (matcher.find()) {
                listImgSrc.add(matcher.group().substring(0, matcher.group().length() - 1));
            }
        }
        return listImgSrc;
    }



    public void getOkHttpBitmap(String url) {
//        final Bitmap bitmap = null;
        OkHttpClient okHttpClient = null;
        Request request = null;
        Response response = null;
        Call call = null;
        try {
            okHttpClient = new OkHttpClient();
            request = new Request.Builder()
                    .url(url)
                    .build();


            //3.创建一个Call对象，参数是request对象，发送请求
            call = okHttpClient.newCall(request);

            //4.异步请求，请求加入调度
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    mHandler.sendEmptyMessage(FALL);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //得到从网上获取资源，转换成我们想要的类型  我们得到的信息存储在response中
                    byte[] Picture_bt = response.body().bytes();

                    //通过handler更新UI
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = Picture_bt;
                    mHandler.sendMessage(msg);
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void OnNeedSendMessageForStr(String str) {
        Message message = new Message();
        message.what = 2;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    @Override
    public void OnNeedSendMessageForFAll() {
        mHandler.sendEmptyMessage(FALL);
    }
}
